<template>
  <view class="reapply-container">
    <uni-forms ref="form" :model="form" :rules="rules">
      <view class="form-card">
        <view class="card-header">
          <text class="header-title">补卡申请</text>
        </view>
        
        <view class="card-content">
          <uni-forms-item name="attendanceDate" label="补卡日期">
            <view class="date-picker-custom" @click="openCalendar">
              <view class="picker-value">{{ form.attendanceDate || '请选择补卡日期' }}</view>
              <view class="picker-icon">
                <uni-icons type="calendar" size="18"></uni-icons>
              </view>
            </view>
          </uni-forms-item>
          
          <uni-forms-item name="reapplyType" label="补卡类型">
            <uni-data-checkbox 
              v-model="form.reapplyType" 
              :localdata="reapplyTypeOptions" 
              mode="button"
            />
          </uni-forms-item>
          
          <uni-forms-item name="reapplyTime" label="补卡时间">
            <view class="time-picker-custom" @click="openTimePicker">
              <view class="picker-value">{{ form.reapplyTime || '请选择补卡时间' }}</view>
              <view class="picker-icon">
                <uni-icons type="clock" size="18"></uni-icons>
              </view>
            </view>
          </uni-forms-item>
          
          <uni-forms-item name="reapplyLocation" label="补卡地点">
            <uni-easyinput 
              v-model="form.reapplyLocation" 
              placeholder="请输入补卡地点"
            />
          </uni-forms-item>
          
          <uni-forms-item name="reason" label="补卡原因">
            <uni-easyinput 
              v-model="form.reason" 
              placeholder="请输入补卡原因"
              type="textarea"
            />
          </uni-forms-item>
        </view>
      </view>
      
      <view class="action-buttons">
        <button type="primary" @click="submitForm">提交申请</button>
        <button type="default" @click="cancel">取消</button>
      </view>
    </uni-forms>
    
    <!-- 日期选择器弹窗 -->
    <uni-calendar 
      ref="calendar"
      :insert="false"
      :showMonth="true"
      :range="false"
      :start-date="getStartDate()"
      :end-date="getEndDate()"
      @confirm="onCalendarConfirm"
    />
    
    <!-- 时间选择器弹窗 -->
    <uni-popup ref="timePopup" type="bottom">
      <view class="time-picker-popup">
        <view class="time-picker-header">
          <text class="cancel-btn" @click="cancelTimePicker">取消</text>
          <text class="header-title">选择时间</text>
          <text class="confirm-btn" @click="confirmTimePicker">确认</text>
        </view>
        <picker-view
          class="time-picker-view"
          :value="timePickerValue"
          @change="onTimePickerChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(hour, index) in hours" :key="'hour-'+index">
              {{ hour }}
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(minute, index) in minutes" :key="'minute-'+index">
              {{ minute }}
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(second, index) in seconds" :key="'second-'+index">
              {{ second }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { applyReapply } from "@/api/system/attendance";

export default {
  name: "AttendanceReapply",
  data() {
    return {
      // 表单参数
      form: {
        attendanceDate: '',
        reapplyType: 'in',
        reapplyTime: '',
        reapplyLocation: '公司',
        reason: ''
      },
      // 补卡类型选项
      reapplyTypeOptions: [
        { text: '签到补卡', value: 'in' },
        { text: '签退补卡', value: 'out' }
      ],
      // 表单校验
      rules: {
        attendanceDate: {
          rules: [{
            required: true,
            errorMessage: '请选择补卡日期'
          }]
        },
        reapplyType: {
          rules: [{
            required: true,
            errorMessage: '请选择补卡类型'
          }]
        },
        reapplyTime: {
          rules: [{
            required: true,
            errorMessage: '请选择补卡时间'
          }]
        },
        reapplyLocation: {
          rules: [{
            required: true,
            errorMessage: '请输入补卡地点'
          }]
        },
        reason: {
          rules: [{
            required: true,
            errorMessage: '请输入补卡原因'
          }]
        }
      },
      // 时间选择器数据
      hours: Array.from({length: 24}, (_, i) => i.toString().padStart(2, '0')),
      minutes: Array.from({length: 60}, (_, i) => i.toString().padStart(2, '0')),
      seconds: Array.from({length: 60}, (_, i) => i.toString().padStart(2, '0')),
      timePickerValue: [8, 30, 0], // 默认值 08:30:00
      tempTimeValue: '' // 临时存储时间值
    };
  },
  created() {
    // 初始化表单数据
    this.initFormData();
    // 设置默认时间选择器值
    this.setDefaultTimePickerValue();
  },
  mounted() {
    // 确保组件加载后表单项能正确初始化
    setTimeout(() => {
      if (this.$refs.form) {
        this.$refs.form.setRules(this.rules);
      }
    }, 300);
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      this.form.attendanceDate = this.getCurrentDate();
      this.form.reapplyTime = this.getCurrentTime();
      console.log('初始化数据:', this.form);
    },
    
    // 根据当前时间设置默认的时间选择器值
    setDefaultTimePickerValue() {
      if (this.form.reapplyTime) {
        const timeParts = this.form.reapplyTime.split(':');
        const hours = parseInt(timeParts[0]) || 0;
        const minutes = parseInt(timeParts[1]) || 0;
        const seconds = parseInt(timeParts[2]) || 0;
        this.timePickerValue = [hours, minutes, seconds];
      }
    },
    
    // 打开日历选择器
    openCalendar() {
      this.$refs.calendar.open();
    },
    
    // 打开时间选择器
    openTimePicker() {
      this.setDefaultTimePickerValue();
      this.$refs.timePopup.open();
    },
    
    // 日历确认事件
    onCalendarConfirm(e) {
      const { fulldate } = e;
      if (fulldate) {
        this.form.attendanceDate = fulldate;
        console.log('日期已更新:', fulldate);
      }
    },
    
    // 时间选择器变化事件
    onTimePickerChange(e) {
      const values = e.detail.value;
      const hours = this.hours[values[0]];
      const minutes = this.minutes[values[1]];
      const seconds = this.seconds[values[2]];
      this.tempTimeValue = `${hours}:${minutes}:${seconds}`;
      this.timePickerValue = values;
    },
    
    // 确认时间选择
    confirmTimePicker() {
      if (this.tempTimeValue) {
        this.form.reapplyTime = this.tempTimeValue;
      } else {
        const hours = this.hours[this.timePickerValue[0]];
        const minutes = this.minutes[this.timePickerValue[1]];
        const seconds = this.seconds[this.timePickerValue[2]];
        this.form.reapplyTime = `${hours}:${minutes}:${seconds}`;
      }
      console.log('时间已更新:', this.form.reapplyTime);
      this.$refs.timePopup.close();
    },
    
    // 取消时间选择
    cancelTimePicker() {
      this.tempTimeValue = '';
      this.$refs.timePopup.close();
    },
    
    // 表单提交
    submitForm() {
      this.$refs.form.validate().then(res => {
        console.log('表单验证结果:', res);
        
        if (res) {
          this.$modal.loading("提交中");
          
          // 确保提交的数据是有效的
          if (!this.isValidDatetime()) {
            this.$modal.closeLoading();
            this.$modal.showError("日期或时间格式不正确，请重新选择");
            return;
          }
          
          // 准备提交的数据
          const submitData = {
            attendanceDate: this.form.attendanceDate,
            reapplyType: this.form.reapplyType,
            reapplyTime: this.form.reapplyTime,
            reapplyLocation: this.form.reapplyLocation,
            reason: this.form.reason
          };
          
          console.log('准备提交的数据:', submitData);
          
          // 调用API提交数据
          applyReapply(submitData)
            .then(res => {
              this.$modal.closeLoading();
              console.log('提交响应:', res);
              
              if (res && res.code === 200) {
                // 使用正确的成功提示方法
                uni.showToast({
                  title: "申请提交成功",
                  icon: "success",
                  duration: 2000
                });
                
                // 返回上一页
                setTimeout(() => {
                  this.$tab.navigateBack();
                }, 1500);
              } else {
                this.$modal.showError((res && res.msg) || "申请提交失败");
              }
            })
            .catch(err => {
              console.error("补卡申请失败:", err);
              this.$modal.closeLoading();
              this.$modal.showError("网络错误，请稍后重试");
            });
        } else {
          console.log('表单验证失败:', this.form);
        }
      }).catch(error => {
        console.error('表单验证错误:', error);
        // 使用正确的错误提示方法
        uni.showToast({
          title: "表单验证错误，请检查填写的内容",
          icon: "none",
          duration: 2000
        });
      });
    },
    
    // 校验日期时间格式
    isValidDatetime() {
      // 检查日期格式: yyyy-MM-dd
      const datePattern = /^\d{4}-\d{2}-\d{2}$/;
      // 检查时间格式: HH:mm:ss
      const timePattern = /^\d{2}:\d{2}:\d{2}$/;
      
      return datePattern.test(this.form.attendanceDate) && 
             timePattern.test(this.form.reapplyTime) &&
             !this.form.attendanceDate.includes('NaN') &&
             !this.form.reapplyTime.includes('NaN');
    },
    
    // 取消按钮
    cancel() {
      this.$tab.navigateBack();
    },
    
    // 获取当前日期
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 获取当前时间
    getCurrentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    },
    
    // 获取起始日期（近30天）
    getStartDate() {
      const date = new Date();
      date.setDate(date.getDate() - 30);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 获取结束日期（未来30天）
    getEndDate() {
      const date = new Date();
      date.setDate(date.getDate() + 30);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.reapply-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.form-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  
  .card-header {
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    margin-bottom: 15px;
    
    .header-title {
      font-size: 18px;
      font-weight: bold;
    }
  }
}

.date-picker-custom, .time-picker-custom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 35px;
  padding: 0 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  
  .picker-value {
    flex: 1;
    font-size: 14px;
    color: #333;
    
    &:empty::before {
      content: attr(placeholder);
      color: #999;
    }
  }
  
  .picker-icon {
    width: 20px;
    text-align: center;
    color: #666;
  }
}

.time-picker-popup {
  background-color: #fff;
  border-radius: 10px 10px 0 0;
  overflow: hidden;
  
  .time-picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    padding: 0 15px;
    border-bottom: 1px solid #eee;
    
    .header-title {
      font-size: 16px;
      font-weight: bold;
    }
    
    .cancel-btn, .confirm-btn {
      font-size: 14px;
      padding: 10px;
    }
    
    .cancel-btn {
      color: #666;
    }
    
    .confirm-btn {
      color: #007aff;
    }
  }
  
  .time-picker-view {
    height: 250px;
    
    .picker-item {
      height: 44px;
      line-height: 44px;
      text-align: center;
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  
  button {
    width: 48%;
    height: 45px;
    font-size: 16px;
  }
}
</style> 